package com.dhecp.project.logstics.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.dhecp.common.annotation.Log;
import com.dhecp.common.annotation.RepeatSubmit;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.core.page.TableDataInfo;
import com.dhecp.common.enums.BusinessType;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.ModuleTable;
import com.dhecp.core.layui.GridColumnsPropertyModel;
import com.dhecp.core.utils.ExportExcelUtils;
import com.dhecp.project.api.util.ApiConfig;
import com.dhecp.project.business.domain.FbaLogsticsOrder;
import com.dhecp.project.business.domain.FbaLogsticsOrderDetail;
import com.dhecp.project.business.domain.FbaLogsticsOrderSelect;
import com.dhecp.project.business.mapper.FbaLogsticsOrderDetailMapper;
import com.dhecp.project.common.controller.BaseModuleController;
import com.dhecp.project.logstics.domain.FbaLogisticsReconcileSon;
import com.dhecp.project.logstics.domain.FbaSpellTicket;
import com.dhecp.project.logstics.mapper.FbaLogisticsReconcileSonMapper;
import com.dhecp.project.logstics.service.FbaLogisticsOrderService;
import com.dhecp.project.logstics.service.FbaLogsticsOrderBoxService;
import com.dhecp.project.system.domain.SysDictionaryForExport;
import com.dhecp.project.system.service.SysDictionaryForFieldService;

/**
 * @program: kjecp
 * @description: 物流拼票 控制层
 * @author: fxz
 * @create: 2022-10-25 15:13
 */
@Controller
@RequestMapping("/logstics/fbaLogisticsOrder")
public class FbaLogisticsOrderController extends BaseModuleController {

    private String prefix = "logstics/fbaLogisticsOrder";
    private String moduleTable1 = ModuleTable.FBA_LOGSTICSORDER;
    private String moduleTable_XDMX = ModuleTable.FBA_LOGSTICSORDERDETAIL;

    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;

    @Autowired
    private FbaLogisticsOrderService fbaLogisticsOrderService;

    @Autowired
    private GridColumnsPropertyModel gridColumnsPropertyModel;

    @Autowired
    private FbaLogsticsOrderDetailMapper fbaLogsticsOrderDetailMapper;

    @Autowired
    private FbaLogsticsOrderBoxService fbaLogsticsOrderBoxService;

    @Autowired
    private FbaLogisticsReconcileSonMapper fbaLogisticsReconcileSonMapper;




    /**
     * @Description: 打开查询列表页
     * @Param: [params]
     * @return: org.springframework.web.servlet.ModelAndView
     * @Author: hlf
     * @date: 2022-08-15 15:42
     */
    @RequiresPermissions("logstics:fbaLogisticsOrder:view")
    @GetMapping()
    public ModelAndView view(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable1);
        params.put("entity", new FbaLogsticsOrder()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
        params.put("prefix", prefix + "/fbaLogisticsOrder"); //页面路径
        params.put("toolBarWidth", 0);
        params.put("checkBox", "yes");

        ModelAndView mv = this.openListPage(params);
        params.put("moduleTable", moduleTable_XDMX);
        params.put("entity", new FbaLogsticsOrderDetail());
        Object importFields = dictionaryForFieldService.queryFieldFrontImport(params); //导入模板字段
        //导入批量标记发货模板
        Map<String, Object> params1 = new HashMap<String, Object>();
        params1.put("moduleTable", moduleTable1);
        params1.put("entity", new FbaLogsticsOrder());
        //导入标记发货模板
        Object importFieldFH = dictionaryForFieldService.queryFieldFrontImport(params1);
        mv.addObject("importFieldFH", importFieldFH);
        mv.addObject("importFieldYDH", importFieldFH);
        mv.addObject("importFields", importFields);	//导入模板字段
        mv.addObject("logstics", "fbaLogisticsOrder");
        mv.addObject("ali1688EcpApiUrl", ApiConfig.getAli1688EcpApiUrl());
        return mv;
    }

    /**
     * @Description: 查询页 列表数据
     * @Param: [params]
     * @return: com.dhecp.common.core.page.TableDataInfo
     * @Author: hlf
     * @date: 2022-08-15 15:43
     */
    @RequiresPermissions("logstics:fbaLogisticsOrder:list")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable1);
        List<FbaLogsticsOrder> list = new ArrayList<FbaLogsticsOrder>();
        try {
            list = fbaLogisticsOrderService.queryList(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());
        }
        return getDataTable(list);
    }

    /**
     * @Description: 查询页 子列表数据
     * @Param: [params]
     * @return: com.dhecp.common.core.page.TableDataInfo
     * @Author: fxz
     * @date: 2023-05-15 15:42
     */
    @RequiresPermissions("logstics:fbaLogisticsOrder:list")
    @GetMapping("/sonlist")
    @ResponseBody
    public AjaxResult sonlist(@RequestParam Map<String, Object> params) {

        try {
            AjaxResult ajaxResult = new AjaxResult();
            Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
            Map<String, Object> mapList = new HashMap<>();
            Map<String, Object> stringObjectMap = new HashMap<>();
            params.put("toolBarWidth", 0);
            params.put("moduleTable", moduleTable_XDMX);
            params.put("entity", new FbaLogsticsOrderDetail()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
            params.put("codeFbaLogsticsOrder",params.get("code"));
            params.remove("code");
            mapList.put("sonList", fbaLogsticsOrderDetailMapper.select(params));
            stringObjectMap = gridColumnsPropertyModel.queryGridColumnsPropertyModel(params);
            mapList.put("fields", TypeUtils.mapToJson(dictionaryForFieldMap));
            mapList.put("gridColumns", stringObjectMap);
            ajaxResult = AjaxResult.success(mapList);
            return ajaxResult;
        } catch (Exception e) {
            return AjaxResult.error(this.getExceptionMessage(e));
        }
    }

    /**
     * 美标箱规
     * @param request
     * @return
     */
    @RequestMapping("/astm")
    public ModelAndView toYys(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        try {
            FbaLogsticsOrderDetail fbaLogsticsOrderDetail = JSON.parseObject(request.getParameter("infoMap"), FbaLogsticsOrderDetail.class);
            Map<String, Object> params = new HashMap<>();
            params.put("logsticsOrderDetailGuid",fbaLogsticsOrderDetail.getGuid());
            params.put("num","3");
            ModelAndView mv = new ModelAndView();
            if (fbaLogsticsOrderDetail.getCreationMethod().equals("手动")){
                mv.addObject("infoItems", fbaLogsticsOrderBoxService.queryList(params));
            } else {
                mv.addObject("infoItems", fbaLogsticsOrderBoxService.queryAutoList(params));
            }
            mv.addObject("infoMap", fbaLogsticsOrderDetail);
            if (fbaLogsticsOrderDetail.getCreationMethod().equals("手动")){
                mv.setViewName(prefix + "/astm");
            }else {
                mv.setViewName(prefix + "/astmZd");
            }
            return mv;
        } catch (Exception e) {
            e.printStackTrace();
            return null;    //详细信息
        }
    }

    /**
     * @Description: 打印发票清单
     * @Param: [params]
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: fxz
     * @date: 2023-05-24 14:55
     */
    @RequiresPermissions("logstics:fbaLogisticsOrder:list")
    @Log(title = "打印发票清单", businessType = BusinessType.EXPORT)
    @PostMapping("/printList")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult printList(@RequestParam Map<String, Object> params) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = fbaLogisticsOrderService.printList(params);
        } catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * @Description: 数据导出Excel
     * @Param: [params]
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: fxz
     * @date: 2023-11-04 15:43
     */
    @RequiresPermissions("logstics:fbaLogisticsOrder:export")
    @Log(title = "物流订单数据导出", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult export(@RequestParam Map<String, Object> params) throws Exception {
       params.put("moduleTable", moduleTable1);
    	params.put("entity", new FbaLogsticsOrder());
        List<FbaLogsticsOrder> list = fbaLogisticsOrderService.queryList(params);
        params.put("getFieldAttributesType", "export");
    	List<SysDictionaryForExport> fieldList = dictionaryForFieldService.queryExportFieldList(params);
        ExportExcelUtils<FbaLogsticsOrder> util = new ExportExcelUtils<FbaLogsticsOrder>(moduleTable1,new FbaLogsticsOrder());
        return util.exportExcel(list, fieldList, "物流订单数据", "export");
    }

    /**
     * 导出Excel导入模板
     * @param params
     * @return
     * @throws Exception
     * @author fxz
     */
    @RequiresPermissions("logstics:fbaLogisticsOrder:import")
    @Log(title = "物流订单数据导出", businessType = BusinessType.EXPORT)
    @GetMapping("/exporttemplate")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult exportTemplate(@RequestParam Map<String, Object> params) throws Exception {
        params.put("moduleTable", moduleTable_XDMX);
        params.put("entity", new FbaLogsticsOrderDetail());
        String sheetName = "追踪编号导入模板";
        if (params.get("num").equals("5")){
            params.put("moduleTable", moduleTable1);
            params.put("entity", new FbaLogsticsOrder());
            sheetName = "批量标记发货模板";
        }else if (params.get("num").equals("6")){
            params.put("moduleTable", moduleTable1);
            params.put("entity", new FbaLogsticsOrder());
            sheetName = "批量导入运单号模板";
        }
        params.put("getFieldAttributesType", "template");
        List<SysDictionaryForExport> fieldList = dictionaryForFieldService.queryExportFieldList(params);
        if (params.get("num").equals("5")){
            fieldList = fieldList.subList(0,1);
        }
        ExportExcelUtils<FbaLogsticsOrderDetail> util = new ExportExcelUtils<FbaLogsticsOrderDetail>(moduleTable_XDMX,new FbaLogsticsOrderDetail());
        return util.exportExcel(null, fieldList, sheetName, "template");
    }

    /**
     * 导入并直接回填追踪编号单据
     * @param params 必要参数：对应实体类的json格式字符串（导入的字段用户内容）
     * @return
     * @throws Exception
     * @author fxz
     */
    @Log(title = "物流订单追踪编号导入", businessType = BusinessType.EXPORT)
    @PostMapping("/importdatapost")
    @ResponseBody
    public AjaxResult importData(@RequestParam Map<String, Object> params) throws Exception {
        params.put("moduleTable", moduleTable1);

        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= fbaLogisticsOrderService.importData(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * @Description: 回退
     * @Param: infoItems 必要参数：对应实体类的json格式字符串
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: fxz
     * @date: 2023-05-25 15:44
     */
    @RequiresPermissions(value = {"logstics:fbaLogisticsOrder:add"}, logical = Logical.OR)
    @Log(title = "物流订单回退", businessType = BusinessType.UPDATE)
    @PostMapping("/htbtn")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult htbtn(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable1);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = fbaLogisticsOrderService.htbtn(params);
        } catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 批量标记发货状态
     * @param params 必要参数：对应实体类的json格式字符串（导入的字段用户内容）
     * @return
     * @throws Exception
     * @author fxz
     */
    @Log(title = "批量标记发货状态", businessType = BusinessType.EXPORT)
    @PostMapping("/batchDelivery")
    @ResponseBody
    public AjaxResult batchDelivery(@RequestParam Map<String, Object> params) throws Exception {
        params.put("moduleTable", moduleTable1);

        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= fbaLogisticsOrderService.batchDelivery(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 标记发货
     * @param params
     * @return
     */
    @PostMapping("/isShipments")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult isShipments(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable1);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = fbaLogisticsOrderService.isShipments(params);
        } catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 物流订单导入运单号
     * @param params
     * @return
     */
    @RequiresPermissions(value = {"logstics:fbaLogisticsOrder:add"}, logical = Logical.OR)
    @Log(title = "物流订单导入运单号", businessType = BusinessType.UPDATE)
    @PostMapping("/waybillNumber")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult waybillNumber(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable1);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = fbaLogisticsOrderService.waybillNumber(params);
        } catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 批量导入运单号状态
     * @param params 必要参数：对应实体类的json格式字符串（导入的字段用户内容）
     * @return
     * @throws Exception
     * @author fxz
     */
    @Log(title = "批量导入运单号状态", businessType = BusinessType.EXPORT)
    @PostMapping("/importWaybillNumber")
    @ResponseBody
    public AjaxResult importWaybillNumber(@RequestParam Map<String, Object> params) throws Exception {
        params.put("moduleTable", moduleTable1);

        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= fbaLogisticsOrderService.importWaybillNumber(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * @Description: 查询页 列表数据
     * @Param: [params]
     * @return: com.dhecp.common.core.page.TableDataInfo
     * @Author: fxz
     * @date: 2023-06-08
     */
    @RequiresPermissions("logstics:fbaLogisticsOrder:list")
    @GetMapping("/logsticsOrderList")
    @ResponseBody
    public TableDataInfo logsticsOrderList(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable1);
        List<FbaLogsticsOrderSelect> list = new ArrayList<FbaLogsticsOrderSelect>();
        List<FbaLogisticsReconcileSon> fbaLogisticsReconcileSonList = fbaLogisticsReconcileSonMapper.queryListCode(params.get("codereconcile").toString());
        StringBuffer sb = new StringBuffer();
        StringBuffer sbHw = new StringBuffer();
        for (FbaLogisticsReconcileSon fbaLogisticsReconcileSon : fbaLogisticsReconcileSonList){
            if (fbaLogisticsReconcileSon.getType().equals("0") ){
                sb.append(fbaLogisticsReconcileSon.getLogisticsOrderCode()).append(",");
            }else {
                sbHw.append(fbaLogisticsReconcileSon.getLogisticsOrderCode()).append(",");
            }
        }
        String codereconcile = " (t1.state = 0 AND (t1.stateTrack = 3 OR t1.stateTrack = 4))";
        String codereconcileHw = " (t2.stateName = '已发货')";
        if (sb.length() != 0){
            String sb1 = sb.toString().substring(0,sb.length()-1);
            codereconcile = "t1.code in ('" + sb1.replace(",", "','") + "')";
        }
        if (sbHw.length() != 0){
            String sb1Hw = sbHw.toString().substring(0,sbHw.length()-1);
            codereconcileHw = "t2.bid in ('" + sb1Hw.replace(",", "','") + "')";
        }
        params.put("codereconcile", codereconcile);
        params.put("codereconcileHw", codereconcileHw);

        try {
            list = fbaLogisticsOrderService.queryListSelect(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());
        }
        return getDataTable(list);
    }

    /**
     *@Description: 查询已选择的商品
     *@Param: selectedUser ：已选中的商品编号字符串，示例：0000,1001,1002
     *@return: com.dhecp.common.core.page.TableDataInfo
     *@Author: hlf
     *@date: 2022-08-18 17:13
     */
    @GetMapping("/listselect")
    @ResponseBody
    public TableDataInfo userInfoSelectListJson(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable1);
        List<FbaLogsticsOrderSelect> list = new ArrayList<FbaLogsticsOrderSelect>();
        if (params.get("selectedUser") != null && params.get("selectedUser") != ""){
            String wherestrhand = "t1.code in ('" + params.get("selectedUser").toString().replace(",", "','") + "')";
            String wherestrhandHW = "t2.bid in ('" + params.get("selectedUser").toString().replace(",", "','") + "')";
            params.put("wherestrhand", wherestrhand);
            params.put("wherestrhandHW", wherestrhandHW);
            try{
                list = fbaLogisticsOrderService.queryListSelect(params);
            }catch(Exception e){
                return getDataTable(this.getExceptionMessage(e).toString());
            }
        }else{
            return getDataTable("请传入已选中的商品编码字符串（selectedUser），取值示例：0000,1001,1002");
        }
        return getDataTable(list);
    }

    @RequiresPermissions("logstics:fbaLogisticsOrder:list")
    @GetMapping("/details")
    @ResponseBody
    public TableDataInfo details(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable1);
        List<FbaSpellTicket> list = new ArrayList<FbaSpellTicket>();
        try {
            list = fbaLogisticsOrderService.details(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());
        }
        return getDataTable(list);
    }


    /**
     * 物流订单上传C88数据
     * @param params
     * @return
     */
    @RequiresPermissions(value = {"logstics:fbaLogisticsOrder:add"}, logical = Logical.OR)
    @Log(title = "物流订单上传C88数据", businessType = BusinessType.UPDATE)
    @PostMapping("/entryNumber")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult entryNumber(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable1);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = fbaLogisticsOrderService.entryNumber(params);
        } catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }
}